package org.yun.octopus.base.core;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.yun.octopus.base.spi.ICorrect;
import org.yun.octopus.base.spi.IMarkCache;
import org.yun.octopus.base.spi.IRollback;
import org.yun.octopus.base.util.SystemTimer;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

import static org.yun.octopus.base.config.Cfg.interval;
import static org.yun.octopus.base.config.Cfg.suspend;
import static org.yun.octopus.base.core.RollbackFactory.GROUP_STEPS_MAP;
import static org.yun.octopus.base.enums.CallType.SYNC_ALL;

/**
 * 纠正异常数据
 * @author liyunfeng31
 */
@Component
public class CorrectHandler implements ICorrect {

     protected static final Logger LOG = LoggerFactory.getLogger(CorrectHandler.class);

     @Resource
     private IRollback handler;

     @Resource
     private IMarkCache markCache;


     /**
      * N分钟执行一次扫描
      * @param start 开始时间
      * @param end 结束时间
      */
     @Override
     public void correctExData(long start, long end, String group, int shardingNo) {

          if(start == 0 || end == 0){
               end = SystemTimer.currentTime() - suspend;
               start = end - interval;
          }

          if(group != null){
               findAndHandler(start, end, group);
               return;
          }

          Set<String> groups = GROUP_STEPS_MAP.keySet();
          for(String gp : groups){
               findAndHandler(start, end, gp);
          }
     }




     private void findAndHandler(long start, long end, String group){

          List<Object> bizNos = markCache.abnormalNos(group, start, end, 100);
          if(CollectionUtils.isEmpty(bizNos)){
               return;
          }
          for (Object bizNo : bizNos) {
               try {
                    handler.execute(group,bizNo.toString(), SYNC_ALL.code());
               } catch (Exception e) {
                    LOG.error("CorrectTask exception, group:{}, bizNo:{}",group, bizNo, e);
               }
          }
     }

}
